package com.cbtx.networklib.log

import com.cbtx.networklib.constant.TagConstant.MJ_REQUEST
import com.cbtx.networklib.constant.TagConstant.MJ_RESPONSE
import okhttp3.Headers
import okhttp3.internal.platform.Platform
import okhttp3.logging.HttpLoggingInterceptor

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/7/1 10:12 AM
 * desc   :
 */
class LogBuilder {

    var tag = "LogBuilder"
    var isDebug = false
    var type = Platform.INFO
    var requestTag: String = MJ_REQUEST
    var responseTag: String = MJ_RESPONSE
    var level = HttpLoggingInterceptor.Level.BASIC
    var builder: Headers.Builder? = null
    var logger: Logger? = null
    var prettyJsonPrinting = true

    constructor() {
        builder = Headers.Builder()
    }

    fun getHeaders(): Headers? {
        return builder!!.build()
    }

    fun getTag(isRequest: Boolean): String {
        return if (isRequest) {
            requestTag
        } else {
            responseTag
        }
    }

    /**
     * @param name  Filed
     * @param value Value
     * @return Builder
     * Add a field with the specified value
     */
    fun addHeader(name: String, value: String): LogBuilder {
        builder!![name] = value
        return this
    }

    /**
     * @param level set log level
     * @return Builder
     */
    fun setLevel(level: HttpLoggingInterceptor.Level): LogBuilder {
        this.level = level
        return this
    }

    /**
     * Set request and response each log tag
     *
     * @param tag general log tag
     * @return Builder
     */
    fun tag(tag: String): LogBuilder {
        this.tag = tag
        return this
    }

    /**
     * Set request log tag
     *
     * @param tag request log tag
     * @return Builder
     */
    fun request(tag: String): LogBuilder {
        requestTag = tag
        return this
    }

    /**
     * Set response log tag
     *
     * @param tag response log tag
     * @return Builder
     */
    fun response(tag: String): LogBuilder {
        responseTag = tag
        return this
    }

    /**
     * @param isDebug set can sending log output
     * @return Builder
     */
    fun loggable(isDebug: Boolean): LogBuilder {
        this.isDebug = isDebug
        return this
    }

    /**
     * @param type set sending log output type
     * @return Builder
     * @see Platform
     */
    fun log(type: Int): LogBuilder {
        this.type = type
        return this
    }

    /**
     * @param logger manuel logging interface
     * @return Builder
     * @see Logger
     */
    fun logger(logger: Logger): LogBuilder {
        this.logger = logger
        return this
    }

    fun prettyJsonPrinting(prettyJsonPrinting: Boolean): LogBuilder {
        this.prettyJsonPrinting = prettyJsonPrinting
        return this
    }
}
